<template>
    <div class="login_container">
      <el-row>
        <el-col :span="12" :xs="0"></el-col>
        <el-col :span="12" :xs="24">
          <el-form v-if="showLogin" class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
            <h2>卫星仿真平台</h2>
            <el-form-item prop="username">
              <el-input
                :prefix-icon="User"
                v-model="loginForm.username"
                ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                :prefix-icon="Lock"
                v-model="loginForm.password"
                show-password
                ></el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <div style="display: flex; gap: 10px;">
                <el-input
                  v-model="loginForm.captcha"
                  placeholder="请输入验证码"
                  style="flex: 1"
                ></el-input>
                <img :src="captchaUrl" 
                     @click="getCaptcha"
                     style="width: 120px; height: 40px; background: #f5f5f5; cursor: pointer;"
                     alt="验证码">
              </div>
            </el-form-item>
            <el-form-item>
              <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="login">
                登录
              </el-button>
            </el-form-item>
            <div class="register_link">
              <span @click="showLogin = false">未有账户？点击注册</span>
            </div>
          </el-form>

          <el-form v-else class="login_form" :model="registerForm" :rules="rules" ref="registerForms">
            <h2>卫星仿真平台</h2>
            <el-form-item prop="username">
              <el-input
                :prefix-icon="User"
                v-model="registerForm.username"
                placeholder="请输入用户名"
                ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                :prefix-icon="Lock"
                v-model="registerForm.password"
                placeholder="请输入密码"
                show-password
                ></el-input>
            </el-form-item>
            <el-form-item prop="confirmpassword">
              <el-input
                type="password"
                :prefix-icon="Lock"
                v-model="registerForm.confirmpassword"
                placeholder="请确认密码"
                show-password
                ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="register">
                注册
              </el-button>
            </el-form-item>
            <div class="register_link">
              <span @click="showLogin = true">已有账户？点击登录</span>
            </div>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </template>
  
<script setup lang="ts">
    import { User, Lock } from '@element-plus/icons-vue'
    import { reactive,ref } from 'vue'
    import { reqRegister, reqCaptcha } from '@/api/user'
    import type { AxiosError } from 'axios'
    const showLogin = ref(true)
    import { useRouter } from 'vue-router'
    import { ElNotification } from 'element-plus'
    //引入用户相关的小仓库
    import useUserStore from '@/store/modules/user'
    //引入获取当前时间的函数
    import { getTime } from '@/utils/time'

    //获取el-form组件
    let loginForms = ref()
    let registerForms = ref()
    //引入小仓库
    let useStore = useUserStore()
    //获取路由器
    let $router = useRouter()
    //定义变量控制按钮加载效果
    let loading = ref(false)
    //收集账号与密码数据
    let loginForm = reactive({ username: 'admin', password: '123123', captcha: '' })
    let registerForm = reactive({ username: '', password: '', confirmpassword: '' })
    let captchaUrl = ref('')
    let captchaId = ref('') // Store captcha ID for validation
    
    // 获取验证码
    const getCaptcha = async () => {
      try {
        const response = await reqCaptcha()
        const blobUrl = URL.createObjectURL(response.data)
        captchaUrl.value = blobUrl
      } catch (error: unknown) {
        console.error('Captcha error:', error)
        const err = error as AxiosError | Error
        ElNotification({
          type: 'error',
          message: '获取验证码失败: ' + (err.message || '未知错误')
        })
        // Show default error image
        captchaUrl.value = ''
      }
    }
    
    // 初始化验证码
    getCaptcha()
    //登录按钮回调
    const login = async()=>{
      //保证全部表单相校验通过再发请求
      await loginForms.value.validate()
      //按钮加载效果
      loading.value = true
        try{
          //保证登录成功
          await useStore.userLogin({
            username: loginForm.username,
            password: loginForm.password,
            captcha: loginForm.captcha
          })
          //编成式导航跳转到展示数据页面
          $router.push('/home')
          //登录成功提示信息
          ElNotification({
            type: 'success',
            message: '欢迎你',
            title:`Hi,${getTime()}好`
          })
          //登录成功按钮加载效果消失
          loading.value = false
        }catch(error){
          //登录失败按钮加载效果消失
          loading.value = false
          //登录失败的提示信息
          ElNotification({
            type:'error',
            message:(error as Error).message
          })
        }
    }

    //注册方法
    const register = async () => {
      try {
        await registerForms.value.validate()
        loading.value = true
        await reqRegister({
          username: registerForm.username,
          password: registerForm.password,
          confirmpassword: registerForm.confirmpassword
        })
        ElNotification({
          type: 'success',
          message: '注册成功',
          title: '提示'
        })
        // Clear form and switch to login
        registerForm.username = ''
        registerForm.password = ''
        registerForm.confirmpassword = ''
        showLogin.value = true
        loading.value = false
      } catch (error) {
        loading.value = false
        ElNotification({
          type:'error',
          message:(error as Error).message
        })
      }
    }

    //自定义校验规则函数
    const validatorUserName=(rule:any,value:any,callback:any)=>{
      //rule:即为校验规则对象
      //value:即为表单元素文本内容
      //如果符合条件callback放行通过，不符合callback注入错误提示信息
      if(value.length>=2){
        callback()
      }else{
        callback(new Error('账号长度至少五位'))
      }
    }
    const validatorPassword=(rule:any,value:any,callback:any)=>{
      const trimmedValue = value?.trim()
      if(!trimmedValue){
        callback(new Error('请输入密码'))
      }else if(trimmedValue.length < 6){
        callback(new Error('密码长度至少六位'))
      }else if(trimmedValue.length > 20){
        callback(new Error('密码长度不能超过20位'))
      }else{
        callback()
      }
    }
    //密码确认验证
    const validateConfirmPassword = (rule: any, value: any, callback: any) => {
      if (value !== registerForm.password) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }

    //定义表单检验需要配置对象
    const rules = {
      confirmpassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ],
      username:[
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {trigger:'blur',validator:validatorUserName}
      ],
      password:[
        {required: true, message: '请输入密码', trigger: 'blur'},
        {trigger:'submit',validator:validatorPassword}
      ],
      captcha: [
        {required: true, message: '请输入验证码', trigger: 'blur'}
      ]
    }
</script>
  
<style lang="scss" scoped>
    .login_container {
      width: 100%;
      height: 100vh;
      background: url('@/assets/images/504.jpg') no-repeat center center;
      background-size: cover;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.3);
      }
      .login_form {
        width: 400px;
        padding: 30px;
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        h1 {
          color: #333;
          font-size: 24px;
          text-align: center;
          margin-bottom: 20px;
        }
        h2 {
          color: #666;
          font-size: 16px;
          text-align: center;
          margin-bottom: 30px;
        }
        .el-input {
          margin-bottom: 20px;
          :deep(.el-input__wrapper) {
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            &:hover {
              box-shadow: 0 0 0 1px #c0c4cc inset;
            }
          }
        }
        .login_btn {
          width: 100%;
          background-color: #409EFF;
          border-color: #409EFF;
          &:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
          }
        }
      }
    }
    .register_link {
      text-align: right;
      margin-top: 10px;
      span {
        color: #409EFF;
        cursor: pointer;
        font-size: 14px;
        &:hover {
          text-decoration: underline;
        }
      }
    }
</style>
